<?php

declare(strict_types=1);

namespace App\Resource\Service;

use App\Common\Constants\ErrorCode;
use App\Common\Service\BaseService;
use App\Resource\Model\MenuModel;

class MenuService extends BaseService
{
    /**
     * @param array $where
     *
     * @return array
     */
    public function getList(array $where)
    {
        $query = MenuModel::query();
        !empty($where['title']) && $query->whereRaw('INSTR(title, ?) > 0', [$where['title']]);
        $Rdata = $this->redis->hGet('Menu', 'list');
        if (empty($where['title']) && !empty($Rdata)) {
            return ['code' => ErrorCode::SUCCESS, 'data' => json_decode($Rdata, true)];
        }
        $list = $query->orderBy('sort', 'desc')->get()->toArray();
        if (!empty($list)) {
            $list = $this->generateTree($list, 'pid');
        }
        $this->redis->hSet('Menu', 'list', json_encode($list));
        return ['code' => ErrorCode::SUCCESS, 'data' => $list];
    }

    /**
     * @return array
     */
    public function getParIndex()
    {
        $query = MenuModel::query();
        $query->where('url', '=', '#');
        $query->where('status', '=', '1');
        $list = $query->orderBy('id', 'asc')->get(['id', 'pid', 'title'])->toArray();
        if (!empty($list)) {
            $list = $this->generateTree($list, 'pid');
        }
        return ['code' => ErrorCode::SUCCESS, 'data' => $list];
    }

    /**
     * @param array $params
     *
     * @return array
     */
    public function add(array $params)
    {
        $res = MenuModel::create($params);
        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => []];
        }
        return ['code' => ErrorCode::NOT_IN_FORCE];
    }

    /**
     * @param array $params
     *
     * @return array
     */
    public function update(array $params)
    {
        $res = MenuModel::where(['id' => $params['id']])->update($params);
        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => []];
        }
        return ['code' => ErrorCode::NOT_IN_FORCE];
    }

    /**
     * @param int $id
     *
     * @return mixed
     */
    public function delete(int $id)
    {
        $haschild = MenuModel::where(['pid' => $id])->first();
        if ($haschild) {
            return ['code' => ErrorCode::DELETE_REFUSE];
        }
        $res = MenuModel::where('id', $id)->delete();
        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => []];
        }
        return ['code' => ErrorCode::NOT_IN_FORCE];
    }

}
